package com.auth.service.impl;

import com.auth.entity.dao.RoleAuthority;
import com.auth.entity.dto.AuthorityDto;
import com.auth.mapper.RoleAuthorityMapper;
import com.auth.service.IAuthorityService;
import com.auth.service.IRoleAuthorityService;
import com.auth.util.MybaitsUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.auth.entity.factory.AuthorityFactory.AUTHORITY_CONVERTER;

@Service
@RequiredArgsConstructor
public class RoleAuthorityServiceImpl extends ServiceImpl<RoleAuthorityMapper, RoleAuthority> implements IRoleAuthorityService {
    @Autowired
    private IAuthorityService iAuthorityService;

    @Override
    public void removeByRoleId(Integer id) {
        remove(new QueryWrapper<RoleAuthority>().eq("rid", id));
    }

    @Override
    public void removeByAuthorityId(Integer id) {
        remove(new QueryWrapper<RoleAuthority>().eq("aid", id));
    }

    @Transactional
    @Override
    public void releaseAuthorityToRole(Integer roleId, List<Integer> authorityIdList) {
        if (authorityIdList == null) {
            return;
        }
        //跳过已经赋予的权限
        for (Integer id : authorityIdList) {
            if (!MybaitsUtils.existCheck(this, Map.of("rid", roleId, "aid", id))
            &&MybaitsUtils.existCheck(iAuthorityService,Map.of("id",id))) {
                save(RoleAuthority.builder().aid(id).rid(roleId).build());
            }
        }
    }

    @Transactional
    @Override
    public void revokeAuthorityFromRole(Integer roleId, List<Integer> authorityIdList) {
        if (authorityIdList == null) {
            return;
        }
        for (Integer id : authorityIdList) {
            remove(new QueryWrapper<RoleAuthority>().eq("rid", roleId).eq("aid", id));
        }
    }

    @Override
    public List<AuthorityDto> getAuthorityOfRole(Integer roleId) {
        List<Integer> aIdList = listByMap(Map.of("rid", roleId)).stream().map(RoleAuthority::getAid).collect(Collectors.toList());
        return ObjectUtils.isEmpty(aIdList)?null:AUTHORITY_CONVERTER.toListAuthorityDto(iAuthorityService.listByIds(aIdList));
    }
}
